<?php
declare (strict_types=1);

namespace app\sysuser\controller\core;

use app\common\controller\SysBackend;
use app\common\model\banxi\core\CoreBrokerageWithdraw as CoreBrokerageWithdrawModel;
use app\common\model\banxi\organization\Organization;
use app\common\service\core\BrokerageService;
use ba\Exception;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class CoreBrokerageWithdraw extends SysBackend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new CoreBrokerageWithdrawModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->with([
            'organizationBaseInfo' => function ($query) {
                $query->field('id,name,managerName');
            }])->where($where)
            ->order(['id' => 'asc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ])->each(function ($item) {
                if ($item['organizationId'] == 0) {
                    $organization = new Organization();
                    $item->organizationBaseInfo = $organization->getOrganizationInfo();
                }
            });
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);
        $info = $this->model->with([
            'organizationBaseInfo' => function ($query) {
                $query->field('id,name,managerName');
            }])->where($where)->find();
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        if ($info['organizationId'] == 0) {
            $organization = new Organization();
            $info->organizationBaseInfo = $organization->getOrganizationInfo();
        }
        $this->ok('操作成功', $info);
    }

    public function withdrawAudit()
    {
        // 配置为生成19位数字ID的示例
        $param = $this->request->param(["id" => 0, 'result', 'rejectReason' => '', 'payVoucher' => '']);
        try {
            $validate = Validate::rule([
                'id' => ValidateRule::isRequire(null, '请选择提现记录'),
                'result' => ValidateRule::in([true, false], '请设置正确的审核状态'),
                'rejectReason' => ValidateRule::requireIf(['result', false], '请填写拒绝理由'),
                'payVoucher' => ValidateRule::requireIf(['result', true], '请上传打款凭证'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $brokerageService = new BrokerageService();
            $res = $brokerageService->withdrawAudit($param['id'], $param['result'], $param['rejectReason'], $param['payVoucher']);
            if(!$res){
                throw new ValidateException($brokerageService->getError());
            }
        } catch (PDOException|Exception|ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功');
    }
}
